<?php 
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;
use DB;
use Schema;
//处理 分表的增删查改 以及连表 

class Fenbiao extends Model {

    // protected $connection='jmft_uc';

    // protected $redis;

      /*
    * protected $splitTable = 'cdb_honey_log'; 原始表
    * protected $splitTableNameRule = '_Yn'; 分表名称规则
    * protected $splitTableMode = 'month'; 分表方式 year, month, day
    * const CREATED_AT; 数据的添加时间字段，最好用回laravel自带的
    * protected $dateFormat = 'U' 时间戳
    */


    public function __construct() {

    	$this->splitTableMode = 'month';
    	$this->splitTable = 'log';
    	$this->splitTableNameRule = '_Yn';

    	// $this->table = $this->splitTable . Carbon::now()->format($this->splitTableNameRule);
    	// if (!Schema::hasTable($this->table))
     //    {
     //        DB::update('create table '.$this->table.' like logs');
     //    }
    	//print_r($this->table);
    	

    }


    //添加数据的时候 需要验证 是否有该表 
    protected function Createtable(){
    	$createtable = $this->splitTable .Carbon::now()->format($this->splitTableNameRule);
    	if (!Schema::hasTable($this->table))
        {
            $res = DB::update('create table '.$createtable.' like logs');
            echo $res;
        }
        echo 2222;
        exit;
        return ;
    }

    //单独查询 单表 
    public function Singledata(){

    }

    //添加数据  (没有要创建表)
    public function Add($param){
    	echo 1111;
    	exit;
    	self::Createtable();
    	

    	

    }



    //连表查询（列表这一块 条件为整体查询 ）  
    public function setUnionAllTable($start = null, $end = null, $colums = '*', $where = '1'){
    	
    	 // 开始日期,和日期有关的，都建议用内置的carbon处理，非常好用，而且简洁
        $start = is_numeric($start) ? Carbon::createFromTimestamp($start) : Carbon::parse($start);
        // 结束日期
        $end = is_numeric($end) ? Carbon::createFromTimestamp($end) : Carbon::parse($end);

        echo $start;

       
         // 循环规则
        switch ($this->splitTableMode) {
            case 'year':
                $loopFormat = 'Y';
                $loopIncrement = 'addYear';
                $startOf = 'startOfYear';
                break;
            case 'month':
                $loopFormat = 'Y-m';
                $loopIncrement = 'addMonth';
                $startOf = 'startOfMonth';
                break;
            case 'day':
                $loopFormat = 'Y-m-d';
                $loopIncrement = 'addDay';
                $startOf = 'startOfDay';
                break;
        }


        
        $dateFormat = $this->dateFormat ? $this->dateFormat : 'Y-m-d H:i:s';

        $betweenDate = [$start->format($dateFormat), $end->format($dateFormat)];
        print_r($betweenDate);
         exit;

        // 判断是否需要联合查询
        /*
         if ($start->format($loopFormat) == $end->format($loopFormat))

            return $this->setTable("{$this->splitTable}{$start->format($this->splitTableNameRule)}")
                ->selectRaw($colums)
                ->whereBetween(self::CREATED_AT, $betweenDate)
                ->whereRaw($where);
                */

        // 查询集合
        $queries = collect();


        // 循环比较，添加每一张表的查询
        for ($i = $start->copy()->$startOf(); $i->format($loopFormat) <= $end->format($loopFormat); $i->$loopIncrement()) {
           // dd($betweenDate);
            $queries->push(
                DB::table("{$this->splitTable}{$i->format($this->splitTableNameRule)}")
                    // 建议都用select查询字段，SQL尽可能的优化性能
                    ->selectRaw($colums)
                    ->whereBetween(self::CREATED_AT, $betweenDate)
                    ->whereRaw($where)
            );
        }

        // 出列一张表作为union的开始
        $unionQuery = $queries->shift();

        // 循环剩下的表添加union
        $queries->each(function ($item, $key) use ($unionQuery) {
            $unionQuery->unionAll($item);
        });
        	return $this->setTable($this->splitTable)
            ->from(DB::raw("({$unionQuery->toSql()}) as {$this->splitTable}"))
            // 合并查询条件
            ->mergeBindings($unionQuery);

    }


    
}